package com.lee.mq.mqserver.datacenter;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-10-24
 * Time: 15:37
 */

import com.lee.mq.common.MqException;
import com.lee.mq.mqserver.core.Binding;
import com.lee.mq.mqserver.core.Exchange;
import com.lee.mq.mqserver.core.MSGQueue;
import com.lee.mq.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 通过这个类管理所有硬盘上的数据
 * 1.数据库: 交换机, 队列,  绑定
 * 2.文件: 消息
 */

public class DiskDataCenter {
    // 这个实例用来管理数据库中的数据
    private DataBaseManager dataBaseManager = new DataBaseManager();
    // 这个实例用来管理文件中的数据
    private MessageFileManager messageFileManager = new MessageFileManager();

    // 1.封装对以上两个实例的初始化操作
    public void init() {
        // 针对数据库实例进行初始化(建库建表)
        dataBaseManager.init();
        // 针对文件实例进行初始化(当前并未实现，便于后续拓展)
        messageFileManager.init();
    }

    // 2.封装交换机操作
    public int insertExchange(Exchange exchange) {
        return dataBaseManager.insertExchange(exchange);
    }

    public int deleteExchange(String exchangeName) {
        return dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExcanges() {
        return dataBaseManager.selectAllExchanges();
    }

    // 3.封装队列操作
    public int insetQueue(MSGQueue queue) throws IOException, MqException {
        // 同时创建队列对应的目录和文件
        messageFileManager.createQueueFiles(queue.getName());
        return dataBaseManager.insertQueue(queue);
    }

    public int deleteQueue(String queueName) throws IOException {
        // 同时删除对列对应的目录和文件
        messageFileManager.destoryQueueFiles(queueName);
        return dataBaseManager.deleteQueue(queueName);
    }

    public List<MSGQueue> selectAllQueues() {
        return dataBaseManager.selectAllQueues();
    }

    // 4.封装绑定操作
    public int insetBinding(Binding binding) {
        return dataBaseManager.insertBinding(binding);
    }

    public int deleteBinding(Binding binding) {
        return dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings() {
        return dataBaseManager.selectAllBindings();
    }

    // 5.封装消息操作
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue,message);
    }

    public void deleteMessage(MSGQueue queue,Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(queue,message);
        // 删除文件后检查GC
        boolean res = messageFileManager.checkGC(queue.getName());
        if (res) {
            messageFileManager.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromFile(String queueName) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromFile(queueName);
    }
}
